package com.haochang.chunkvod.controller.activity.cash;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseEditText;
import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.utils.SaleUtils;
import com.haochang.chunkvod.app.utils.TimeUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.app.utils.VodDialog;
import com.haochang.chunkvod.model.cash.CashData;
import com.haochang.chunkvod.model.cash.GoodInfo;
import com.haochang.chunkvod.model.cash.NonOperateEnum;
import com.haochang.chunkvod.model.cash.PrintEnum;
import com.haochang.chunkvod.model.cash.PrintInfo;
import com.haochang.chunkvod.model.cash.ThirdEnum;
import com.haochang.chunkvod.tools.thirdparty.lakala.PrintDataUtils;
import com.haochang.chunkvod.tools.thirdparty.zxing.view.CaptureActivity;
import com.haochang.chunkvod.tools.vod.log.Logger;
import com.haochang.chunkvod.tools.vod.thread.PrintThread;
import com.haochang.chunkvod.tools.vod.thread.ThreadPoolUtil;
import com.haochang.chunkvod.view.vod.dialog.DialogItemInfo;
import com.haochang.chunkvod.view.vod.dialog.KeyBoardDialog;
import com.haochang.chunkvod.view.vod.dialog.SingleSelectionDialog;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;

/**
 * @author qintao
 *         created at 2016/8/2 10:43
 *         结算--营业外商品结算/赔偿结算
 */

public class SettlementActivity extends BaseActivity implements KeyBoardDialog.KeyBoardOnSureListener
{
	private TitleView titleView;
	private BaseTextView tv_receivable, tv_received;
	private BaseTextView tv_change, tv_unreceived;
	private BaseEditText et_cash, et_memberCard, et_thirdParty;
	private BaseTextView tv_thirdParty;
	private Button btn_pend, btn_checkOut_pay;
	private CheckBox item_cb;
	private NonOperateEnum nonOperateEnum;
	private String title;
	private int currentViewId = 0;
	private List<DialogItemInfo> thirdPayList = new ArrayList<DialogItemInfo>();
	private CashData cashData;
	private int total;
	private int unreceived;
	private int received;
	private int cash;
	private int card;
	private int thirdParty;
	private String QR_code;
	private String thirdType = ThirdEnum.ALI_PAY.getName();
	private ArrayList<GoodInfo> goodsInfoList = new ArrayList<GoodInfo>();

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	}

	@Override
	public void receiveParam()
	{
		total = getIntent().getIntExtra(IntentKey.PRICEVALUE, 0);
		unreceived = total;//进入页面时默认未收等于应收
		goodsInfoList = getIntent().getParcelableArrayListExtra(IntentKey.GOODS_LIST);
		nonOperateEnum = (NonOperateEnum) getIntent().getSerializableExtra(IntentKey.ACTIVITY_ENUM);
		if (nonOperateEnum == NonOperateEnum.NON_OPERATE)
			title = "营业外商品结算";
		else
			title = "赔偿结算";
	}

	@Override
	public void initData()
	{
		cashData = new CashData(SettlementActivity.this);
		DialogItemInfo itemInfo1 = new DialogItemInfo(ThirdEnum.ALI_PAY.getName(), "支付宝", true);
		DialogItemInfo itemInfo2 = new DialogItemInfo(ThirdEnum.WEI_XIN_PAY.getName(), "微信", false);
		DialogItemInfo itemInfo3 = new DialogItemInfo(ThirdEnum.CARD.getName(), "刷卡", false);
		thirdPayList.add(itemInfo1);
		thirdPayList.add(itemInfo2);
		thirdPayList.add(itemInfo3);
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_settlement);
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle(title).setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				finish();
			}

			@Override
			public void onDoneClick()
			{
				List<String> list = new ArrayList<String>();
				list.add("退出登录");
				int location[] = new int[2];
				ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
				img.getLocationOnScreen(location);
				int x = location[0];
				final VodPopWindow pop = new VodPopWindow(SettlementActivity.this, list);
				pop.showPopupWindow(titleView, x);
				pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
				{
					@Override
					public void onSelectItem(int position)
					{
						switch (position)
						{
						case 0:
							loginOut();
							break;
						default:
							break;
						}
					}
				});
			}
		});
		tv_receivable = (BaseTextView) findViewById(R.id.tv_receivable);
		tv_received = (BaseTextView) findViewById(R.id.tv_received);
		tv_unreceived = (BaseTextView) findViewById(R.id.tv_unreceived);
		tv_change = (BaseTextView) findViewById(R.id.tv_change);
		tv_receivable.setText(String.format("应收：%s", SaleUtils.getSaleString(total)));
		tv_received.setText(String.format("实收：%s", "0"));
		tv_unreceived.setText(String.format("未收：%s", SaleUtils.getSaleString(total)));
		et_cash = (BaseEditText) findViewById(R.id.et_cash);
		et_memberCard = (BaseEditText) findViewById(R.id.et_memberCard);
		et_thirdParty = (BaseEditText) findViewById(R.id.et_thirdParty);
		et_cash.setOnClickListener(mOnBaseClickListener);
		et_memberCard.setOnClickListener(mOnBaseClickListener);
		et_thirdParty.setOnClickListener(mOnBaseClickListener);
		et_cash.addTextChangedListener(textWatcher);
		et_memberCard.addTextChangedListener(textWatcher);
		et_thirdParty.addTextChangedListener(textWatcher);
		tv_thirdParty = (BaseTextView) findViewById(R.id.tv_thirdParty);
		tv_thirdParty.setOnClickListener(mOnBaseClickListener);
		btn_pend = (Button) findViewById(R.id.btn_pend);
		btn_checkOut_pay = (Button) findViewById(R.id.btn_checkOut_pay);
		btn_pend.setOnClickListener(mOnBaseClickListener);
		btn_checkOut_pay.setOnClickListener(mOnBaseClickListener);
		item_cb = (CheckBox) findViewById(R.id.item_cb);
		item_cb.setChecked(true);
		if (nonOperateEnum == NonOperateEnum.NON_OPERATE)
		{
			item_cb.setVisibility(View.GONE);
			btn_pend.setVisibility(View.VISIBLE);
		} else
		{
			item_cb.setVisibility(View.VISIBLE);
			btn_pend.setVisibility(View.GONE);
		}
		View line_bottom = findViewById(R.id.line_bottom);
		RelativeLayout public_comment_div_one = (RelativeLayout) findViewById(R.id.public_comment_div_one);
		RelativeLayout public_comment_div_two = (RelativeLayout) findViewById(R.id.public_comment_div_two);
		line_bottom.setVisibility(View.GONE);
		public_comment_div_one.setVisibility(View.GONE);
		public_comment_div_two.setVisibility(View.GONE);
	}

	private OnBaseClickListener mOnBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.tv_thirdParty:
				new SingleSelectionDialog.Builder(SettlementActivity.this).dialogEnum(SingleSelectionDialog.DialogEnum.PAY).setTitle(R.string.thirdPay)
						.setSingleChoiceItems(thirdPayList, new SingleSelectionDialog.OnSelectListener()
						{
							@Override
							public void getValue(String code, String name)
							{
								if (!TextUtils.isEmpty(name))
								{
									tv_thirdParty.setText(name);
									thirdType = code;
								}
							}
						}).createDialog().show();
				break;
			case R.id.et_cash:
				currentViewId = R.id.et_cash;
				showKeyBoardDialog();
				break;
			case R.id.et_memberCard:
				ToastUtils.showText(SettlementActivity.this, "暂未开发此功能");
				//				currentViewId = R.id.et_memberCard;
				//				showKeyBoardDialog();
				break;
			case R.id.et_thirdParty:
				currentViewId = R.id.et_thirdParty;
				showKeyBoardDialog();
				break;
			case R.id.btn_pend:
				checkOut();
				break;
			case R.id.btn_checkOut_pay:
				checkOut();
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 自定义键盘输入
	 */
	private void showKeyBoardDialog()
	{
		KeyBoardDialog keyBoardDialog = new KeyBoardDialog(SettlementActivity.this);
		keyBoardDialog.setKeyBoardOnSureListener(SettlementActivity.this);
		keyBoardDialog.show();
	}

	@Override
	public void setValue(String value)
	{
		if (value.contains("."))
			ToastUtils.showText(SettlementActivity.this, R.string.error_number);
		else if (value.length() > 9)
			ToastUtils.showText(SettlementActivity.this, R.string.error_max_number);
		else
			switch (currentViewId)
			{
			case R.id.et_cash:
				et_cash.setText(value);
				break;
			case R.id.et_memberCard:
				et_memberCard.setText(value);
				break;
			case R.id.et_thirdParty:
				et_thirdParty.setText(value);
				break;
			default:
				break;
			}
	}

	/**
	 * 二维码扫码
	 */
	private void scanQRCode()
	{
		Intent intent = new Intent();
		intent.setClass(SettlementActivity.this, CaptureActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivityForResult(intent, IntentCode.QR_CODE_REQUEST);
	}

	/**
	 * 结算操作
	 */
	private void checkOut()
	{
		if (unreceived > 0)
		{
			ToastUtils.showText(SettlementActivity.this, "还有未收金额，无法结算");
		} else if (unreceived < 0)
		{
			ToastUtils.showText(SettlementActivity.this, "实收金额大于应收金额，无法结算");
		} else
		{
			//执行结算,如果第三方支付金额大于0，且支付类型不为刷卡,进行扫码
			if (thirdParty > 0)
			{
				if (!thirdType.equals(ThirdEnum.CARD.getName()))
					scanQRCode();
				else
					requestLaKaLaPay();
			} else
			{
				if (nonOperateEnum == NonOperateEnum.NON_OPERATE)
				{
					nonOperCheckOutRequest();
				} else
				{
					checkOutRequest();
				}
			}
		}
	}

	/**
	 * 刷卡调用拉卡拉 请求支付
	 */
	private void requestLaKaLaPay()
	{
		try
		{
			ComponentName component = new ComponentName("com.lkl.cloudpos.payment", "com.lkl.cloudpos.payment.activity.MainMenuActivity");
			Intent intent = new Intent();
			intent.setComponent(component);
			Bundle bundle = new Bundle();
			bundle.putString("msg_tp", "0200");
			bundle.putString("pay_tp", "0");
			bundle.putString("proc_tp", "00");
			bundle.putString("proc_cd", "000000");
			bundle.putString("amt", SaleUtils.getSaleString(thirdParty / 100));
			bundle.putString("appid", "com.haochang.chunkvod");
			bundle.putString("time_stamp", TimeUtils.getTimeStr());
			intent.putExtras(bundle);
			this.startActivityForResult(intent, IntentCode.LAKALA_REQUEST);
		} catch (ActivityNotFoundException e)
		{
			e.printStackTrace();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 赔偿结算请求
	 */
	private void checkOutRequest()
	{
		cashData.requestPayForGoodsCheckOut(cash, thirdType, thirdParty, QR_code, getGoodsDetails(), new CashData.INonOperatingRevenueCheckOutListener()
		{
			@Override
			public void onRequestSuccess()
			{
				ToastUtils.showText(SettlementActivity.this, "收款成功");
				VodDialog.closeDialog(VodDialog.DialogEnum.LOADING_PAY);
				if (item_cb.isChecked())
				{
					PrintInfo printInfo = new PrintInfo();
					printInfo.setType(PrintEnum.PRINT_PAY.getName());
					printInfo.setContent(PrintDataUtils.createPaiedData(goodsInfoList, SaleUtils.getSaleString(received)).toString());
					ThreadPoolUtil.getInstanceSingleTaskExecutor().submit(new PrintThread(PrintEnum.PRINT_PAY, printInfo));
				}
				finish();
			}

			@Override
			public void onRequestFail(int errno, String errMsg)
			{
				ToastUtils.showText(SettlementActivity.this, "收款失败");
				VodDialog.closeDialog(VodDialog.DialogEnum.LOADING_PAY);
			}
		});
	}

	/**
	 * 营业外商品结算请求
	 */
	private void nonOperCheckOutRequest()
	{
		cashData.requestNonOperatingRevenueGoodsCheckOut(cash, thirdType, thirdParty, QR_code, getGoodsDetails(),
				new CashData.INonOperatingRevenueCheckOutListener()
				{
					@Override
					public void onRequestSuccess()
					{
						ToastUtils.showText(SettlementActivity.this, "收款成功");
						VodDialog.closeDialog(VodDialog.DialogEnum.LOADING_PAY);
						finish();
					}

					@Override
					public void onRequestFail(int errno, String errMsg)
					{
						ToastUtils.showText(SettlementActivity.this, "收款失败");
						VodDialog.closeDialog(VodDialog.DialogEnum.LOADING_PAY);
					}
				});
	}

	private String getGoodsDetails()
	{
		JSONArray JsonArray = new JSONArray();
		for (int i = 0; i < goodsInfoList.size(); i++)
		{
			GoodInfo goodInfo = goodsInfoList.get(i);
			if (goodInfo.getOrderNum() > 0)
			{
				JSONObject jsonObject = new JSONObject();
				try
				{
					jsonObject.put("id", goodInfo.getGoodsId());
					jsonObject.put("name", goodInfo.getGoodsName());
					jsonObject.put("unit", goodInfo.getUnit());
					jsonObject.put("value", goodInfo.getPrice());
					jsonObject.put("quantity", goodInfo.getOrderNum());
					JsonArray.put(jsonObject);
				} catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
		}
		Logger.e(JsonArray.toString());
		return JsonArray.toString();
	}

	private TextWatcher textWatcher = new TextWatcher()
	{
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after)
		{

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count)
		{

		}

		@Override
		public void afterTextChanged(Editable s)
		{
			cash = TextUtils.isEmpty(et_cash.getText().toString()) ? 0 : SaleUtils.getSaleInt(et_cash.getText().toString());
			card = TextUtils.isEmpty(et_memberCard.getText().toString()) ? 0 : SaleUtils.getSaleInt(et_memberCard.getText().toString());
			thirdParty = TextUtils.isEmpty(et_thirdParty.getText().toString()) ? 0 : SaleUtils.getSaleInt(et_thirdParty.getText().toString());
			received = cash + card + thirdParty;
			unreceived = total - received;
			tv_received.setText(String.format("实收：%s", SaleUtils.getSaleString(received)));
			tv_unreceived.setText(String.format("未收：%s", unreceived < 0 ? "0" : SaleUtils.getSaleString(unreceived)));
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == IntentCode.QR_CODE_REQUEST && resultCode == RESULT_OK && data != null)
		{
			Bundle bundle = data.getExtras();
			QR_code = bundle.getString("result");
			if (TextUtils.isEmpty(QR_code))
			{
				ToastUtils.showText(SettlementActivity.this, "二维码为空");
			} else
			{
				if (nonOperateEnum == NonOperateEnum.NON_OPERATE)
				{
					nonOperCheckOutRequest();
				} else
				{
					checkOutRequest();
				}
			}
		} else if (requestCode == IntentCode.LAKALA_REQUEST && resultCode == RESULT_OK)
		{
			//支付成功
			Logger.e("支付成功");
			ToastUtils.showText(SettlementActivity.this, "支付成功");
			thirdParty = 0;
			if (cash > 0)
			{
				if (nonOperateEnum == NonOperateEnum.NON_OPERATE)
				{
					nonOperCheckOutRequest();
				} else
				{
					checkOutRequest();
				}
			} else
			{
				setResult(RESULT_OK, getIntent());
				finish();
			}
		} else if (requestCode == IntentCode.LAKALA_REQUEST && resultCode == RESULT_CANCELED)
		{
			Logger.e("支付取消");
			Bundle bundle = data.getExtras();
			String reason = bundle.getString("reason");
			if (!TextUtils.isEmpty(reason))
			{
				ToastUtils.showText(SettlementActivity.this, reason);
			}
		} else if (requestCode == IntentCode.LAKALA_REQUEST && resultCode == -2)
		{
			//交易失败
			Bundle bundle = data.getExtras();
			String reason = bundle.getString("reason");
			if (!TextUtils.isEmpty(reason))
			{
				ToastUtils.showText(SettlementActivity.this, reason);
			}
		}
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
	}
}
